import type { RouteRecordRaw, Router } from 'vue-router';

import { usePermissionStoreWithOut } from '../../store/modules/permission';
import { PageEnum } from '../../enums/pageEnum';
import { useUserStoreWithOut } from '../../store/modules/user';

const LOGIN_PATH = PageEnum.BASE_LOGIN;

const whitePathList: PageEnum[] = [LOGIN_PATH];

export function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut()();
  const permissionStore = usePermissionStoreWithOut();

  // 添加全局导航钩子
  router.beforeEach(async (to, from, next) => {
    console.log("路由守卫：当前路径", to.path, "来源路径:", from.path);

    // 白名单可以直接进入
    if (whitePathList.includes(to.path as PageEnum)) {
      if (to.path === LOGIN_PATH && userStore.getAccessToken) {
        const isSessionTimeout = userStore.getSessionTimeout;
        try {
          await userStore.afterLoginAction();
          if (!isSessionTimeout) {
            next((to.query?.redirect as string) || '/');
            return;
          }
        } catch {}
      }
      next();
      return;
    }

    // token不存在 - 打印更多信息便于调试
    if (!userStore.getAccessToken) {
      console.log("路由守卫：无token，需要重定向到登录页");

      // 可以不需要权限访问。需要设置路由元信息ignoreAuth为true
      if (to.meta.ignoreAuth) {
        console.log("路由守卫：路由设置为不需要鉴权，允许继续");
        next();
        return;
      }

      // 重定向登录页面
      const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
        path: LOGIN_PATH,
        replace: true,
      };

      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }

      console.log("路由守卫：执行重定向到登录页", redirectData);
      next(redirectData);
      return;
    }

    // 获取用户信息，上次获取时间为空
    if (userStore.getLastUpdateTime === 0) {
      try {
        await userStore.getUserInfoAction();
      } catch (err) {
        next();
        return;
      }
    }

    if (permissionStore.getIsDynamicAddedRoute) {
      next();
      return;
    }

    const routes = await permissionStore.buildRoutesAction();

    routes.forEach((route) => {
      try {
        router.addRoute(route as unknown as RouteRecordRaw);
      } catch (e) {}
    });

    permissionStore.setDynamicAddedRoute(true);

    if (to.name === 'PageNotFound') {
      // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
      next({ path: to.fullPath, replace: true, query: to.query });
    } else {
      const redirectPath = (from.query.redirect || to.path) as string;
      const redirect = decodeURIComponent(redirectPath);
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
      next(nextData);
    }
  });
}
